﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.ProductionPlanAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command
{
    public class CreateProductionPlanCommand : ProductionPlanEditRequestDto,
        IRequest<Result<ProductionPlanInfoResponseDto>>
    {
    }

    public class CreateProductionPlanCommandHandler : IRequestHandler<CreateProductionPlanCommand,
        Result<ProductionPlanInfoResponseDto>>
    {
        private readonly IProductionPlanRepository _productionPlanRepository;
        private readonly IMapper _mapper;

        public CreateProductionPlanCommandHandler(IProductionPlanRepository productionPlanRepository,
            IMapper mapper)
        {
            _productionPlanRepository = productionPlanRepository;
            _mapper = mapper;
        }

        public async Task<Result<ProductionPlanInfoResponseDto>> Handle(CreateProductionPlanCommand request,
            CancellationToken cancellationToken)
        {
            var productionPlanAggregate = new ProductionPlan(request.Code, request.Name,
                request.OrderId, request.OrderCode, request.PlanType,
                request.DocketDate, request.DocketStatus, request.ExpectStartDate, request.ExpectEndDate,
                request.PriorityLevel, request.ScheduleType,
                request.StandardBomId, request.StandardBomCode, request.StandardBomName, request.Quality, request.Description);


            _productionPlanRepository.Add(productionPlanAggregate);

            await _productionPlanRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<ProductionPlanInfoResponseDto>.SuccessAsync(
                _mapper.Map<ProductionPlanInfoResponseDto>(productionPlanAggregate));
        }
    }
}